package com.lottery.ruok.lottrey.activity;

import android.Manifest;
import android.annotation.SuppressLint;
import android.graphics.Color;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.lottery.ruok.lottrey.BuildConfig;
import com.lottery.ruok.lottrey.R;
import com.lottery.ruok.lottrey.eventbusObject.LocationEvent;
import com.lottery.ruok.lottrey.eventbusObject.LoginDealEvent;
import com.lottery.ruok.lottrey.eventbusObject.LoginSuccess;
import com.lottery.ruok.lottrey.fragment.LoginFragment;
import com.lottery.ruok.lottrey.fragment.RegisterFragment;
import com.lottery.ruok.lottrey.retrofitModule.RetrofitBase;
import com.lottery.ruok.lottrey.retrofitModule.RxHelper;
import com.lottery.ruok.lottrey.retrofitModule.RxSubscribe;
import com.lottery.ruok.lottrey.retrofitModule.request.GetHasSMSRequest;
import com.lottery.ruok.lottrey.retrofitModule.request.GetIsTryStatus;
import com.lottery.ruok.lottrey.retrofitModule.response.GetHasSMSResponse;
import com.lottery.ruok.lottrey.retrofitModule.response.IsTryStatusBean;
import com.lottery.ruok.lottrey.ui.Wave;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import glideHelp.GlideHelper;
import kr.co.namee.permissiongen.PermissionFail;
import kr.co.namee.permissiongen.PermissionGen;
import kr.co.namee.permissiongen.PermissionSuccess;

public class LoginActivity extends BaseActivity {//应该用线性布局的

    @BindView(R.id.logins)
    RelativeLayout logins;
    @BindView(R.id.login_text)
    TextView loginText;
    @BindView(R.id.registers)
    RelativeLayout registers;
    @BindView(R.id.register_text)
    TextView registerText;
    @BindView(R.id.close)
    ImageView close;
    @BindView(R.id.logo_img)
    ImageView logoImg;
    @BindView(R.id.logo_text)
    TextView logoText;
    @BindView(R.id.frame_container)
    FrameLayout mContainer;
    @BindView(R.id.login_image)
    ImageView loginImage;
    @BindView(R.id.register_image)
    ImageView registerImage;
    @BindView(R.id.app_name)
    TextView appName;
    public final static String ANALYTIC_VERSION = "1.0";
    private String mLocation = null;

    private FragmentManager manager;
    private LoginFragment loginFragment;
    private RegisterFragment regFragment;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        ButterKnife.bind(this);
        init();
    }

    @SuppressLint("MissingPermission")
    private void getLocation() {
        LocationManager locationManager;
        locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
        Location location = null;
        try {
            location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (location != null) {
            mLocation = location.getLatitude() + "," + location.getLongitude();
            LocationEvent event = new LocationEvent();
            event.setLocaton(mLocation);
            EventBus.getDefault().post(event);
        }
    }

    private void getLogoInfo() {
        RetrofitBase.getRetrofit().create(GetHasSMSRequest.class).getResult("app_logo")
                .compose(RxHelper.<GetHasSMSResponse>handleResult())
                .subscribe(new RxSubscribe<GetHasSMSResponse>(this) {
                    @Override
                    protected void _onNext(GetHasSMSResponse getHasSMSResponse) {
                        if (getHasSMSResponse != null && getHasSMSResponse.getValue() != null) {
                            if (getHasSMSResponse.getValue().getAsJsonObject().get("list") != null) {
                                if (getHasSMSResponse.getValue().getAsJsonObject().get("list").getAsJsonObject().get("mobile_logo").getAsString() != null) {
                                    if (!isDestroyed()) {
                                        GlideHelper.loadImage(LoginActivity.this, getHasSMSResponse.getValue().getAsJsonObject().get("list").getAsJsonObject().get("mobile_logo").getAsString(), logoImg, R.mipmap.ic_launcher);
                                    }
                                }
                                if (getHasSMSResponse.getValue().getAsJsonObject().get("list").getAsJsonObject().get("mobile_logo_title").getAsString() != null) {
                                    logoText.setText(getHasSMSResponse.getValue().getAsJsonObject().get("list").getAsJsonObject().get("mobile_logo_title").getAsString());
                                }
                            }
                        }
                    }

                    @Override
                    protected boolean showDialog() {
                        return false;
                    }
                });
    }

    private void init() {
        appName.setText(BuildConfig.app_name);
        initFragment();
        getLogoInfo();
        PermissionGen.with(this)
                .addRequestCode(100)
                .permissions(Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION)
                .request();
        EventBus.getDefault().register(this);
        getIsTryStatus();
    }

    /**
     * 初始化要加载的fagment
     */
    private void initFragment() {
        manager = getSupportFragmentManager();
        FragmentTransaction ft = manager.beginTransaction();
        if (loginFragment == null) {
            loginFragment = new LoginFragment();
            ft.add(R.id.frame_container, loginFragment, "login");
        }
        if (regFragment == null) {
            regFragment = new RegisterFragment();
            ft.add(R.id.frame_container, regFragment, "register");
        }
        ft.hide(regFragment);
        ft.commit();
    }

    private void showLogin() {
        FragmentTransaction ft = manager.beginTransaction();
        ft.show(loginFragment);
        ft.hide(regFragment);
        ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
        ft.commitAllowingStateLoss();
    }

    private void showRegister() {
        FragmentTransaction ft = manager.beginTransaction();
        ft.show(regFragment);
        ft.hide(loginFragment);
        ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
        ft.commitAllowingStateLoss();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        PermissionGen.onRequestPermissionsResult(this, requestCode, permissions, grantResults);
    }

    @PermissionSuccess(requestCode = 100)
    public void doSomething() {
        getLocation();
    }

    @PermissionFail(requestCode = 100)
    public void doFailSomething() {

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        EventBus.getDefault().unregister(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(LoginSuccess event) {
        finish();
    }

    @Override
    public void finish() {
        super.finish();
        overridePendingTransition(0, R.anim.anim_exit_from_bottom);
    }

    @OnClick({R.id.close, R.id.logins, R.id.registers})
    public void onViewClicked(View view) {
        removeSoftKeyboard(view);
        switch (view.getId()) {
            case R.id.close:
                finish();
                break;
            case R.id.logins:
                //sendAnalyticMsg("lottery_" + ANALYTIC_VERSION + "_me_setting_login");
                showLogin();
                registerText.setTextColor(getResources().getColor(R.color.text3f));
                loginText.setTextColor(getResources().getColor(R.color.tab_selected));
                loginImage.setVisibility(View.VISIBLE);
                registerImage.setVisibility(View.GONE);

                break;
            case R.id.registers:
                showRegister();
                registerText.setTextColor(getResources().getColor(R.color.tab_selected));
                loginText.setTextColor(getResources().getColor(R.color.text3f));
                loginImage.setVisibility(View.GONE);
                registerImage.setVisibility(View.VISIBLE);
                break;
            case R.id.linear_under_scrollview:
                removeSoftKeyboard(view);
                break;
        }
    }

    /**
     * 获取运营商试玩开关状态
     */
    public void getIsTryStatus() {
        RetrofitBase.getRetrofit().create(GetIsTryStatus.class).getResult()
                .compose(RxHelper.<IsTryStatusBean>handleResultReConnection())
                .subscribe(new RxSubscribe<IsTryStatusBean>(this) {
                    @Override
                    protected void _onNext(IsTryStatusBean chatRoomStatus) {
                        if (chatRoomStatus != null) {
                            LoginDealEvent dealEvent = new LoginDealEvent();
                            switch (chatRoomStatus.getEnable_trial()) {
                                case "1":
                                    dealEvent.setShowBtn(true);
                                    break;
                                case "0":
                                    dealEvent.setShowBtn(false);
                                    break;
                            }
                            EventBus.getDefault().post(dealEvent);
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                    }

                    @Override
                    protected boolean showDialog() {
                        return false;
                    }
                });
    }

}